package rollercoaster.environment.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.media.opengl.GL2ES2;

import rollercoaster.commons.Material;
import rollercoaster.commons.Model;
import rollercoaster.commons.Node;
import rollercoaster.commons.interfaces.NodoProducer;
import rollercoaster.environment.interfaces.IObjFileReader;
import rollercoaster.environment.interfaces.IScenarioReader;

public class EnvironmentModelsProducer implements NodoProducer {

	private IScenarioReader scenarioReader;
	private IObjFileReader modelReader;
	private ModelMaker modelMaker;
	private String defaultTexture;
	private Material mat;
	private String nodeName;
	
	public EnvironmentModelsProducer(IScenarioReader scenarioReader,IObjFileReader modelReader){
		this.scenarioReader=scenarioReader;
		this.modelReader=modelReader;
		this.modelMaker=new ModelMaker(modelReader);
		this.defaultTexture="materials/default.jpg";

	}
	

	public void setNodeName(String nodeName) {
		this.nodeName = nodeName;
	}



	public Node getNode(GL2ES2 gl) {
		HashMap<String, String> modelsList=scenarioReader.getModelsList();
		HashMap<String, HashMap<String, String>> modelsMaterials=scenarioReader.getModelsMaterials();
		List<Model> models=new ArrayList<Model>();
		
		float[] texMatrix={
				1.0f,0,
				0,1.0f
		};

		try {
			modelReader.setFilepath(modelsList.get(nodeName));
			
			Map<String, ArrayList<ObjFace>> map = modelReader.getListModels();
			
			for (Map.Entry<String, ArrayList<ObjFace>> entry : map.entrySet()) {
				
				modelReader.setFaces(entry.getValue());
				Model newModel = modelMaker.makeModel();
				
				HashMap<String, String> materialsList=modelsMaterials.get(nodeName);
				if (materialsList.get(entry.getKey())!=null){
					mat=new Material(materialsList.get(entry.getKey()));
					mat.init(gl);
					mat.setTransformMatrix(texMatrix);
					newModel.setMaterial(mat);
				}
				else {
					Material mat=new Material(defaultTexture);
					mat.init(gl);
					mat.setTransformMatrix(texMatrix);
					newModel.setMaterial(mat);
				}
				newModel.initBuffers(gl);
				newModel.setMaterial(mat);
				models.add(newModel);
			}
			
			
		} catch (Exception e) {
     	System.out.println("Il modello '"+nodeName+"' non è stato trovato nel sistema!");
		}
		
		
		return new Node(models);
	
	}






}
